﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DynamicCombo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            ViewBag.Combos = new ComboSelectedValues
            {
                Cb1 = "10",
                Cb2 = "20",
                Cb3 = "30"
            };

            return View();
        }

      
        public ActionResult Search(string cb1, string cb2, string cb3)
        {
            ViewBag.Combos = new ComboSelectedValues
            {
                Cb1 = cb1, 
                Cb2 = cb2, 
                Cb3 = cb3
            };

            return View("Index");
        }


        public ActionResult About()
        {
            return View();
        }

        public ActionResult Category(int code, int? subcategory)
        {
            if (code == 1)
            {
                return Json( new Item[] { 
                    new Item { val = "10", text = "All" },
                    new Item { val = "11", text = F("C1 - 1", subcategory) },
                    new Item { val = "12", text = F("C1 - 2", subcategory) }
                }, JsonRequestBehavior.AllowGet);
            }
            else if (code == 2)
            {
                return Json(new Item[] { 
                    new Item { val = "20", text = "All" },
                    new Item { val = "21", text = F("C2 - 1", subcategory) },
                    new Item { val = "22", text = F("C2 - 2", subcategory) }
                }, JsonRequestBehavior.AllowGet);
            }

            return Json(new Item[] { 
                    new Item { val = "30", text = "All" },
                    new Item { val = "31", text = F("C3 - 1", subcategory) },
                    new Item { val = "32", text = F("C3 - 2", subcategory) }
                }, JsonRequestBehavior.AllowGet);
        }

        private string F(string a, int? t)
        {
            return "Sub parent for: " + (t != null ? t.ToString() :  "0");
        }
    }

    public class Item
    {
        public string val { get; set; }
        public string text { get; set; }
    }

    public class ComboSelectedValues
    {
        public string Cb1 { get; set; }
        public string Cb2 { get; set; }
        public string Cb3 { get; set; }
    }
}
